package com.codewsq;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPTest {

    /*
     * 发送端
     * */
    @Test
    public void sender() {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket();
            byte[] buffer = "这是一枚UDP方式发射的导弹".getBytes();
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            // UDP的包，UDP连接，包上装着要发送的主机地址和端口，指明什么导弹，打击地址，打击端口位置
            DatagramPacket datagramPacket
                    = new DatagramPacket(buffer, 0, buffer.length, inetAddress, 8090);

            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            datagramSocket.close();
        }
    }

    /*
     * 接收端
     * */
    @Test
    public void receiver() {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(8090);

            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            datagramSocket.receive(packet);

            String str = new String(packet.getData(), 0, packet.getLength());
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            datagramSocket.close();
        }
    }
}
